const fs = require('fs');
const path = require('path');
const exec = require('child_process').exec;

function runLess(rootPath, targetPath) {
    var childArray = fs.readdirSync(rootPath);
    if (childArray.length) {
        for (var i = 0; i < childArray.length; i++) {
            var currentFilePath = path.resolve(rootPath, childArray[i]);
            var currentTargetPath = path.resolve(targetPath, childArray[i]);
            // 读取文件信息
            var stats = fs.statSync(currentFilePath);
            // 若是目录则递归调用
            if (stats.isDirectory()) {
                runLess(currentFilePath, currentTargetPath);
            } else {
                // 判断文件是否为less文件
                if (path.extname(currentFilePath) === '.less') {
                    var newFilePath = path.resolve(targetPath, path.basename(currentFilePath, '.less') + '.css');
                    if (!fs.existsSync(targetPath)) {
                        fs.mkdirSync(targetPath);
                    }
                    exec('lessc ' + currentFilePath + ' > ' + newFilePath);
                }
            }
        }
    }
}

runLess(__dirname, path.resolve(__dirname, '../css/'));
